package personal.xjl.plusdemo.controller;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        String path = request.getRequestURI().toString();
        if(path.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else{
            if(session.getAttribute("username")!=null){
                filterChain.doFilter(servletRequest, servletResponse);
            }
            else
            {
                servletRequest.getRequestDispatcher(request.getContextPath()+"/Student/page.do?page=login").forward(servletRequest, servletResponse);
              //  ((HttpServletResponse)servletResponse).sendRedirect(request.getContextPath()+"/Student/loginNew.do");
                return;
            }
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
